package com.start.cloud.robotcore.properties;

import org.springframework.cloud.config.client.ConfigClientProperties;
import org.springframework.cloud.config.client.ConfigServicePropertySourceLocator;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.mock.env.MockEnvironment;

/**
 * Created by xxu on 2018/4/23.
 */
public class RobotSpringCloudConfigSourceLocator {
    private RobotClientLocalProperties robotProperties;

    private ConfigurableEnvironment env;

    public RobotSpringCloudConfigSourceLocator(RobotClientLocalProperties robotProperties) {
        ConfigurableEnvironment env = new MockEnvironment();
        this.robotProperties = robotProperties;
        this.env = env;
    }

    public RobotSpringCloudConfigSourceLocator(RobotClientLocalProperties robotProperties, ConfigurableEnvironment env) {
        this.robotProperties = robotProperties;
        this.env = env;
    }

    /**
     * 从配置管理中心加载配置文件，并将该配置加入到spring property sources
     *
     * @return
     */
    public org.springframework.core.env.PropertySource<?> locate(final String propertyName) {
        ConfigClientProperties client = new ConfigClientProperties(env) {
            public ConfigClientProperties override(org.springframework.core.env.Environment environment) {
                ConfigClientProperties p = super.override(environment);
                p.setName(propertyName);
                p.setProfile(robotProperties.getEvn());
                return p;
            }
        };
        client.setName(propertyName);
        client.setPassword(robotProperties.getConfigServerPassword());
        client.setProfile(robotProperties.getEvn());
        client.setUri(robotProperties.getConfigServerUrl());
        client.setUsername(robotProperties.getConfigServerUsername());
        client.setLabel("test");
        client.setEnabled(false);
        ConfigServicePropertySourceLocator configServicePropertySourceLocator = new ConfigServicePropertySourceLocator(client);
        org.springframework.core.env.PropertySource<?> properySource = configServicePropertySourceLocator.locate(env);
        if (properySource != null) {
            env.getPropertySources().addFirst(properySource);
        }
        return properySource;
    }
}
